/*
 * Copyright 2011 Dim
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.ratingviewer;

import java.io.File;
import java.util.List;

import javax.swing.*;

import org.htmlparser.lexer.Page;
import org.ratingviewer.data.*;
import org.ratingviewer.data.source.*;
import org.ratingviewer.parser.*;
import org.ratingviewer.ui.RatingViewerMainFrame;

public class RatingViewer {

	private final DataSource dataSource;
	private RatingViewerMainFrame mainFrame;

	public RatingViewer(DataSource dataSource) {
		super();

		if (dataSource == null)
			throw new IllegalArgumentException("Model can't be null.");
		this.dataSource = dataSource;
	}

	public static void main(String[] args) {
		DataSource dataSource = getDataSource();
		RatingViewer ratingViewer = new RatingViewer(dataSource);
		ratingViewer.show();
	}

	private static DataSource getDataSource() {
		String currDir = System.getProperty("user.dir");
		File sourceRoot = new File(currDir, "docs/test-pages");
		DataSource dataSource = new LocalDataSource(sourceRoot, "windows-1251");
		return dataSource;
	}

	private synchronized void show() {
		setupLAF();

		if (mainFrame == null)
			mainFrame = new RatingViewerMainFrame(this);

		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				mainFrame.setLocationByPlatform(true);
				mainFrame.setSize(500, 400);
				mainFrame.setVisible(true);
			}
		});

	}

	private void setupLAF() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException ex) {
			// ignored
		} catch (InstantiationException ex) {
			// ignored
		} catch (IllegalAccessException ex) {
			// ignored
		} catch (UnsupportedLookAndFeelException ex) {
			// ignored
		}
	}

	public void findPlayer(String playerName) {
		try {
			Page resultPage = dataSource.findPlayer(playerName);
			BeregDataParser pageParser = new BeregDataParser(dataSource);
			List<Player> foundPlayers = pageParser.findPlayer(resultPage);
			mainFrame.showPlayers(playerName, foundPlayers);
		} catch (PageGetException ex) {
			mainFrame.showError("message.error-during-search-player", ex, playerName);
		} catch (PageParseException ex) {
			mainFrame.showError("message.error-during-search-player", ex, playerName);
		}

	}
}
